import Vue from "vue";
import store from "@/store";
import VueRouter from "vue-router";

Vue.use(VueRouter);

//重写路由器的push办法
//1.先获取原始的push方法，供自定义push中使用
const lastPush = VueRouter.prototype.push;
//为什么要重写push，因为push方法返回promise实例，但是如果我们不传递第三个参数onAbort，则push内部的catch函数没有处理异常的回调函数，所以如果push出错，就会直接抛出错误到浏览器上
//2.重写push，覆盖之前的push方法，但是我们的push方法默认传入onComplete和onAbort参数的默认参数为一个函数，那么如果push出现问题后，就会有catch的函数帮我们处理异常了，这个就是重写push的核心
VueRouter.prototype.push = function (
  location,
  onComplete = () => {},
  onAbort = () => {}
) {
  /*
  因为之前的push在VueRouter的原型对象上放，所以原本的push中this就是指向VueRouter实例但是现在lastPush被直接默认调用，所以this就指向了undefined了。内部很可能出错，我们在调用lastPush的时候，可以改变他的this指向VueRouter实例
  */
  return lastPush.call(this, location, onComplete, onAbort);
};

const Home = () => import("@pages/Home");
const Login = () => import("@pages/Login");
const Register = () => import("@pages/Register");
const Search = () => import("@pages/Search");
const Detail = () => import("@pages/Detail");
const AddCartSuccess = () => import("@pages/AddCartSuccess");
const ShopCart = () => import("@pages/ShopCart");
const Center = () => import("@pages/Center");
const Pay = () => import("@pages/Pay");
const PaySuccess = () => import("@pages/PaySuccess");
const Trade = () => import("@pages/Trade");
const MyOrder = () => import("@pages/Center/MyOrder");
const TeamOrder = () => import("@pages/Center/TeamOrder");

const router = new VueRouter({
  scrollBehavior() {
    return {
      x: 0,
      y: 0,
    };
  },
  mode: "history",
  routes: [
    {
      path: "/home",
      component: Home,
      name: "home",
    },
    {
      path: "/login",
      component: Login,
      name: "login",
      //配置元信息，控制页脚的显示与隐藏
      meta: {
        footerIsHidden: true,
      },
      beforeEnter(to, from, next) {
        //从vuex里拿到token与用户名
        const token = store.state.user.token;
        if (token) {
          next("/");
        } else {
          next();
        }
      },
    },
    {
      path: "/register",
      component: Register,
      name: "register",
      meta: {
        footerIsHidden: true,
      },
    },
    {
      path: "/search/:keyword?",
      component: Search,
      name: "search",
    },
    {
      path: "/detail/:skuId",
      component: Detail,
      name: "detail",
    },
    {
      path: "/addcartsuccess",
      component: AddCartSuccess,
      name: "addcartsuccess",
      beforeEnter(to, from, next) {
        if (sessionStorage.getItem("cartData")) {
          next();
        } else {
          next("/shopcart");
        }
      },
    },
    {
      path: "/shopcart",
      component: ShopCart,
      name: "shopcart",
    },
    {
      path: "/center",
      component: Center,
      // name: "center",
      children: [
        {
          path: "myorder",
          component: MyOrder,
          name: "myorder",
        },
        {
          path: "teamorder",
          component: TeamOrder,
          name: "teamorder",
        },
        {
          path: "",
          component: MyOrder,
        },
      ],
    },
    {
      path: "/pay",
      component: Pay,
      name: "pay",
      beforeEnter(to, from, next) {
        if (from.path.startsWith("/trade")) {
          next();
        } else {
          next("/shopcart");
        }
      },
    },
    {
      path: "/paysuccess",
      component: PaySuccess,
      name: "paysuccess",
      beforeEnter(to, from, next) {
        if (from.path.startsWith("/paysuccess")) {
          next();
        } else {
          next("/shopcart");
        }
      },
    },
    {
      path: "/trade",
      component: Trade,
      name: "trade",
      beforeEnter(to, from, next) {
        if (from.path.startsWith("/shopcart")) {
          next();
        } else {
          next("/shopcart");
        }
      },
    },
    {
      path: "/",
      redirect: "/home",
    },
  ],
});

router.beforeEach(async (to, from, next) => {
  {
    //创建一个数组，将所有需要token的路由地址保存
    const checkPath = ["/center", "/pay", "/paysuccess", "/trade", "/shopcart"];
    //判断当前访问的路由，是否需要token验证，使用字符串的方法判断开头是否有当前的地址
    const isCheckPath = checkPath.some((item) => {
      return to.path.startsWith(item);
    });
    //从vuex里拿到token与用户名
    const token = store.state.user.token;
    const nickName = store.state.user.nickName;

    //首先判断是否有用户名，如果有用户名说明用户肯定是登陆的，因为用户名是通过我们的token去拿的，那么有用户名直接放行
    if (nickName) {
      return next();
    }
    //判断当前路由是否需要token校验
    if (isCheckPath) {
      if (token) {
        try {
          await store.dispatch("user/getNickName");
        } catch (e) {
          next("/login");
        }
        next();
      } else {
        next("/login");
      }
    } else {
      if (token) {
        try {
          await store.dispatch("user/getNickName");
        } catch (e) {
          next("/login");
        }
      }
      next();
    }
  }
});

export default router;
